/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hirt;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A Basic client that can send and recieve messages from a single server
 * @author zamille
 */
public class Client extends Thread
{
	//MulticastSocket inSocket;
	Socket outSocket = null;
	OutputStream out;

        public Client()
        {
            setupSockets();
           // GUI = myInterface;
        }

        /*
	 * sends a message to the server based on the data in the txt boxes
	 */
	public void sendMessage(Message message)
	{
            byte type = 1;
            //String message = userName + ": " + txtMessage.getText();
            //out.println(type + message);
            //CommunicationAction communique = new CommunicationAction(null, message);
            try {
                System.out.println("Message Type = " + message.type);
                out.write(message.toByte().array());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("Write Error:  " + e.getMessage());
            }

	}

        /**
         * Interprets recieved messages and deals with them accordingly
         * @param buf
         */
	protected void recieveMessage(byte[] buf) {
		//int type = packet.;
		/*Message received = new Message(buf);
		String first = new String(buf, 0, 1);
		byte type = received.type;
		//type is the first part of the message which denotes the type of message
		CommunicationAction message = (CommunicationAction)received.content;
		//recieved is the data that came with the message
		switch (type)
		{
		case 0: 				//close connection message
			//GUI.writeChatMessage("Connection closed\n");
			break;
		case 1: 				//chat message
			//GUI.writeChatMessage(message + "\n");
			break;
		default: System.out.println("Unrecognized type: " + type);
		}*/
	}
        /**
	 * Loops endlessly waiting for message from the server
	 * Is interrupted by action listeners whenever the user does anything
	 *   The class then deals with that
	 *   And when it's done, it goes back to waiting and lstening
	 */
        protected void listen() {
		// TODO Auto-generated method stub
		byte[] buf = new byte[120];
                int result;
		//DatagramPacket packet = new DatagramPacket(buf, buf.length);
		//chatbox.append("System is listening\n");
                InputStream in = null;
                try {
                    in = outSocket.getInputStream();
                } catch (IOException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                }
		//while (true)
		//{
			try
                        {
                                if (in.available() > 0)
                                {
                                    //System.out.println("bytes available");
                                    result = in.read(buf);

                                    //System.out.println ("Network byte result:  " + result);
                                    if (result != 0)
                                    {
                                        recieveMessage(buf);
                                    }
                                }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("Error in receive:   " + e.getMessage());
			}
			
		//}
	}

        /**
	 * instantiates all the socket objects
	 * and connects to the server
	 *
	 * Every statement is surrounded in try catch statements for debugging purposes
	 */
        public void setupSockets()
	{
		/*try {
			//inSocket = new MulticastSocket(4447);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("1: " + e.getMessage());
			return;
		}
                InetAddress address = null;
		try {
			address = InetAddress.getByName("230.0.0.1");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			System.out.println("2: " + e.getMessage());
			return;
		}
        try {
			//inSocket.joinGroup(address);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("3: " + e.getMessage());
			return;
		}*/

        try {
                outSocket = new Socket(ServerConstants.SERVERIPADDRESS, ServerConstants.PORT);
        } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                System.out.println("4: " + e.getMessage());
                return;
        } catch (IOException e) {
            try {
                // TODO Auto-generated catch block
                outSocket = new Socket(ServerConstants.REMOTEIPADDRESS, ServerConstants.PORT);
            } catch (UnknownHostException ex) {
                System.out.println("4.5: " + e.getMessage());
            } catch (IOException ex) {
                try {
                    // TODO Auto-generated catch block
                    outSocket = new Socket(ServerConstants.LOCALIPADDRESS, ServerConstants.PORT);
                } catch (UnknownHostException exp) {
                    System.out.println("4.25: " + exp.getMessage());
                } catch (IOException exp) {
                    System.out.println("5.25: " + exp.getMessage());
                }
                System.out.println("5.5: " + e.getMessage());
            }
                
            
            System.out.println("5: " + e.getMessage());
            
        }
        try {
                out =  outSocket.getOutputStream();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("6: " + e.getMessage());
        }

        //listen();

	}

         /**
	 * Tells the server that the connection is being terminated
	 */
	public void closeConnection()
	{
		try {
			PrintWriter out =  new PrintWriter(outSocket.getOutputStream(), true);
			out.println(0);
			out.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}
}
